use anyhow::Result;
use std::io::{self, Write};
use std::time::{Duration, Instant};
use crate::ftp_client::{FtpClient, TransferResult};

/// 命令行界面工具
pub struct CliInterface {
    show_colors: bool,
    show_progress: bool,
    verbose: bool,
}

impl CliInterface {
    pub fn new() -> Self {
        Self {
            show_colors: true,
            show_progress: true,
            verbose: false,
        }
    }

    pub fn with_colors(mut self, show_colors: bool) -> Self {
        self.show_colors = show_colors;
        self
    }

    pub fn with_progress(mut self, show_progress: bool) -> Self {
        self.show_progress = show_progress;
        self
    }

    pub fn with_verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// 显示连接状态
    pub fn show_connection_status(&self, host: &str, port: u16, connected: bool) {
        let status = if connected {
            self.colorize("✅ Connected", "green")
        } else {
            self.colorize("❌ Disconnected", "red")
        };
        
        println!("🔌 {} to {}:{}", status, host, port);
    }

    /// 显示认证状态
    pub fn show_auth_status(&self, username: &str, authenticated: bool) {
        let status = if authenticated {
            self.colorize("✅ Authenticated", "green")
        } else {
            self.colorize("❌ Not authenticated", "red")
        };
        
        println!("🔐 {} as {}", status, username);
    }

    /// 显示目录信息
    pub fn show_directory_info(&self, path: &str) {
        println!("📁 Current directory: {}", self.colorize(path, "blue"));
    }

    /// 显示文件列表
    pub fn show_file_list(&self, entries: Vec<String>) {
        println!("📋 Directory listing:");
        for entry in entries {
            println!("  {}", entry);
        }
    }

    /// 显示传输进度
    pub fn show_transfer_progress(&self, filename: &str, transferred: u64, total: u64, speed: f64) {
        if !self.show_progress {
            return;
        }

        let percentage = if total > 0 {
            (transferred as f64 / total as f64) * 100.0
        } else {
            0.0
        };

        let progress_bar = self.create_progress_bar(percentage, 30);
        
        print!("\r⬇️ {} [{}] {:.1}% ({}/{}) {:.2} KB/s", 
               filename, progress_bar, percentage, transferred, total, speed / 1024.0);
        io::stdout().flush().unwrap();
    }

    /// 显示传输完成
    pub fn show_transfer_complete(&self, result: &TransferResult) {
        println!(); // 换行
        println!("✅ Transfer completed!");
        println!("  📏 Bytes: {}", self.format_bytes(result.bytes_transferred));
        println!("  ⏱️ Duration: {:.2}s", result.duration.as_secs_f64());
        println!("  🚀 Speed: {:.2} KB/s", result.speed / 1024.0);
        
        if result.resumed {
            println!("  ⏩ Resumed from: {} bytes", result.resume_offset);
        }
        
        if let Some(ref checksum) = result.checksum {
            println!("  🔒 Checksum: {} ({:?})", checksum.checksum, checksum.checksum_type);
        }
        
        if result.integrity_verified {
            println!("  ✅ Integrity: {}", self.colorize("PASSED", "green"));
        } else {
            println!("  ❌ Integrity: {}", self.colorize("FAILED", "red"));
        }
    }

    /// 显示错误信息
    pub fn show_error(&self, message: &str) {
        println!("❌ Error: {}", self.colorize(message, "red"));
    }

    /// 显示警告信息
    pub fn show_warning(&self, message: &str) {
        println!("⚠️ Warning: {}", self.colorize(message, "yellow"));
    }

    /// 显示信息
    pub fn show_info(&self, message: &str) {
        println!("ℹ️ Info: {}", self.colorize(message, "blue"));
    }

    /// 显示成功信息
    pub fn show_success(&self, message: &str) {
        println!("✅ Success: {}", self.colorize(message, "green"));
    }

    /// 显示调试信息
    pub fn show_debug(&self, message: &str) {
        if self.verbose {
            println!("🐛 Debug: {}", self.colorize(message, "magenta"));
        }
    }

    /// 显示帮助信息
    pub fn show_help(&self) {
        println!("🚀 FTP Client Help");
        println!("==================");
        println!();
        println!("Usage: ftp-client [OPTIONS]");
        println!();
        println!("Connection Options:");
        println!("  --host <host>         Server hostname (default: localhost)");
        println!("  --port <port>         Server port (default: 21)");
        println!("  --username <user>     Username for authentication");
        println!("  --password <pass>     Password for authentication");
        println!();
        println!("Transfer Options:");
        println!("  --upload <file>       Upload file to server");
        println!("  --download <file>     Download file from server");
        println!("  --local-path <path>   Local file path for transfers");
        println!("  --no-resume           Disable resume functionality");
        println!("  --checksum <type>     Enable checksum verification (md5, sha256)");
        println!();
        println!("Concurrent Transfer Options:");
        println!("  --concurrent          Enable concurrent transfers");
        println!("  --max-concurrent <n>  Maximum concurrent transfers (default: 3)");
        println!("  --upload-multiple <files>  Upload multiple files (comma-separated)");
        println!("  --download-multiple <files> Download multiple files (comma-separated)");
        println!("  --priority <level>    Transfer priority (low, normal, high, critical)");
        println!();
        println!("UI Options:");
        println!("  --interactive         Start interactive mode");
        println!("  --show-queue          Show transfer queue statistics");
        println!("  --debug               Enable debug logging");
        println!();
        println!("Examples:");
        println!("  ftp-client --interactive");
        println!("  ftp-client --host ftp.example.com --username user --password pass");
        println!("  ftp-client --upload file.txt --local-path ./file.txt");
        println!("  ftp-client --concurrent --upload-multiple file1.txt,file2.txt");
    }

    /// 显示版本信息
    pub fn show_version(&self) {
        println!("FTP Client v{}", env!("CARGO_PKG_VERSION"));
        println!("A high-performance FTP client with encryption plugin support");
    }

    /// 显示传输统计
    pub fn show_transfer_stats(&self, stats: &TransferStats) {
        println!("📊 Transfer Statistics:");
        println!("======================");
        println!("Total transfers: {}", stats.total_transfers);
        println!("Successful: {}", self.colorize(&stats.successful.to_string(), "green"));
        println!("Failed: {}", self.colorize(&stats.failed.to_string(), "red"));
        println!("Total bytes: {}", self.format_bytes(stats.total_bytes));
        println!("Total time: {:.2}s", stats.total_duration.as_secs_f64());
        println!("Average speed: {:.2} KB/s", stats.average_speed / 1024.0);
    }

    /// 显示队列状态
    pub fn show_queue_status(&self, pending: usize, running: usize, completed: usize, failed: usize) {
        println!("📋 Transfer Queue Status:");
        println!("========================");
        println!("Pending: {}", self.colorize(&pending.to_string(), "yellow"));
        println!("Running: {}", self.colorize(&running.to_string(), "blue"));
        println!("Completed: {}", self.colorize(&completed.to_string(), "green"));
        println!("Failed: {}", self.colorize(&failed.to_string(), "red"));
    }

    /// 创建进度条
    fn create_progress_bar(&self, percentage: f64, width: usize) -> String {
        let filled = (percentage / 100.0 * width as f64) as usize;
        let bar = "█".repeat(filled) + &"░".repeat(width - filled);
        bar
    }

    /// 格式化字节数
    fn format_bytes(&self, bytes: u64) -> String {
        if bytes < 1024 {
            format!("{} B", bytes)
        } else if bytes < 1024 * 1024 {
            format!("{:.2} KB", bytes as f64 / 1024.0)
        } else if bytes < 1024 * 1024 * 1024 {
            format!("{:.2} MB", bytes as f64 / (1024.0 * 1024.0))
        } else {
            format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
        }
    }

    /// 颜色化文本
    fn colorize(&self, text: &str, color: &str) -> String {
        if !self.show_colors {
            return text.to_string();
        }

        let color_code = match color {
            "red" => "\x1b[31m",
            "green" => "\x1b[32m",
            "yellow" => "\x1b[33m",
            "blue" => "\x1b[34m",
            "magenta" => "\x1b[35m",
            "cyan" => "\x1b[36m",
            "white" => "\x1b[37m",
            _ => "",
        };

        format!("{}{}\x1b[0m", color_code, text)
    }
}

/// 传输统计信息
#[derive(Debug)]
pub struct TransferStats {
    pub total_transfers: usize,
    pub successful: usize,
    pub failed: usize,
    pub total_bytes: u64,
    pub total_duration: Duration,
    pub average_speed: f64,
}

impl TransferStats {
    pub fn new() -> Self {
        Self {
            total_transfers: 0,
            successful: 0,
            failed: 0,
            total_bytes: 0,
            total_duration: Duration::from_secs(0),
            average_speed: 0.0,
        }
    }

    pub fn add_transfer(&mut self, result: &TransferResult) {
        self.total_transfers += 1;
        if result.integrity_verified {
            self.successful += 1;
        } else {
            self.failed += 1;
        }
        self.total_bytes += result.bytes_transferred;
        self.total_duration += result.duration;
        
        if self.total_duration.as_secs_f64() > 0.0 {
            self.average_speed = self.total_bytes as f64 / self.total_duration.as_secs_f64();
        }
    }
}